package org.libermundi.theorcs.core.tapestry.services.assets;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.tapestry5.ioc.Resource;
import org.apache.tapestry5.ioc.internal.util.AbstractResource;
import org.libermundi.theorcs.core.util.StringListUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.UrlResource;

public class FileResource extends AbstractResource {
	private static final Logger logger = LoggerFactory.getLogger(FileResource.class);

	private File _file;
	
	protected FileResource(String path) {
		super(path.replaceAll("\\\\", "/")); // For Windows environments
		assert StringListUtils.listFirst(path, ":").equals("file");
		try {
			_file = new UrlResource(path).getFile();
		} catch (MalformedURLException e) {
			logger.error("MalformedURLException : " + path, e );
		} catch (IOException e) {
			logger.error("IOException : " + path, e );
		}
	}

	@Override
	public URL toURL() {
		try {
			return _file.toURI().toURL();
		} catch (MalformedURLException e) {
			logger.error("MalformedURLException : " + getPath(), e );
			return null;
		}
	}

	@Override
	protected Resource newResource(String path) {
		return new FileResource(path);
	}

	@Override
	public boolean exists() {
		return _file.exists();
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((_file == null) ? 0 : _file.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		FileResource other = (FileResource) obj;
		if (_file == null) {
			if (other._file != null)
				return false;
		} else if (!_file.equals(other._file))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "file:" + _file.getAbsolutePath();
	}
	
	
	
}
